package org.vectrics.mail.struts;

import javax.servlet.http.HttpServletRequest;

import org.vectrics.SystemException;
import org.vectrics.common.html.TextHelper;
import org.vectrics.common.util.StringUtils;
import org.vectrics.dataweb.WebServiceAction;
import org.vectrics.mail.FileEmailTemplate;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.user.Person;
import org.w3c.dom.Element;

public class FindTemplateWebService extends WebServiceAction {
	public static String COMMAND = "get.email.template";
	
	public FindTemplateWebService() {
		super();
	}

	@Override
	public void getData(Request request, String command,
			Element requestElement, Element responseElement) {
		Element dataElement = this.getDataElement(responseElement);
		if (command.equals(COMMAND)) {
			String templateId = request.getParameter("templateId");
			log.info("Finding template for id = " + templateId);
			if (StringUtils.isNullOrBlank(templateId) == false) {
				FileEmailTemplate template = CoreServiceLocator
					.getSystemService().findFileEmailTemplateWithId(new Long(templateId));
				log.info("Template search (for template Id) - found template: " + template);
				Element templateElement = responseElement.getOwnerDocument().createElement(
						"emailTemplate");
				this.templateToElement(template, templateElement);
				dataElement.appendChild(templateElement);
			} else {
				throw new SystemException("Template ID not found: " + templateId);
			}
		}
	}

	
	private void templateToElement(FileEmailTemplate template, Element element) {
		String text = template.getText();
		if (text == null) {
			text = CoreServiceLocator.getPhraseProvider().getMessage("phrase.template.file.missing", this.getLocale());
		} 
	
		AjaxUtils ajaxUtils = new AjaxUtils();
		text = ajaxUtils.encodeLineBreaks(text);
		
		log.info("Template text: " + text);
		for (int i = 0; i < text.length(); i++) {
			char c = text.charAt(i);
			int r = c;
			log.info("text[" + i + "]: " + c + " #" + r);
		}
				
		
		element.setAttribute("id", template.getId().toString());
		element.setAttribute("text", text);
		element.setAttribute("subject", template.getSubject());
		element.setAttribute("name", template.getName());
		element.setAttribute("description", template.getDescription());
		log.info("returning template XML:" +
				"\r\n - id   = " + template.getId() +
				"\r\n - name   = " + template.getName() +
				"\r\n - text = " + text
				);
	}
}
